﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DIPLib.Filters
{
    public class Erosion
    {
        public static void doIt(byte[] rgbData, int width, int height, byte[] structureMatrix)
        {
            MyBitmap bitmap = new MyBitmap(rgbData, width, height);
            byte[] rgbDataSrc = (byte[])rgbData.Clone();
            //rgbData = new byte[width * height * 4];
            MyBitmap bitmapSrc = new MyBitmap(rgbDataSrc, width, height);
            int matrixSize = (int)Math.Sqrt(structureMatrix.Length);

            byte[] matrix = new byte[matrixSize * matrixSize];

            int radius = matrixSize >> 1;
            for (int row = 1; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    // Fill the matrix
                    int count = 0;
                    bool fit = true;
                    for (int a = 0; a < matrixSize; a++)
                    {
                        if (fit == false)
                        {
                            break;
                        }
                        int ir = row + a - radius;
                        if (ir < 0 || ir >= height)
                        {
                            count += matrixSize;
                            continue;
                            // Ca 1 hang nam ngoai ma tran anh.
                        }
                        for (int b = 0; b < matrixSize; b++)
                        {
                            
                            int jc = col + b - radius;

                            // Neu thu tu cot nam trong ma tran anh, va hang cung nam trong ma tran anh
                            if (jc >= 0 && jc < width)
                            {
                                if (structureMatrix[count] == 1 && bitmapSrc.getPixel(jc, ir) == 255)
                                {
                                    // Do o bitmapSrc, 1 la mau trang => = 0 trong slide => false
                                    fit = false;
                                    break;
                                }
                            }
                            count++;

                        }
                    }
                    if (fit)
                    {
                        bitmap.setPixel(col, row, 0);
                    }
                    else
                    {
                        bitmap.setPixel(col, row, 255);
                    }
                }
            }
        }
    }
}
